package com.personal.gateway.service.impl;

import com.personal.gateway.dto.ContainerGroup;
import com.personal.gateway.service.K8sService;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.openapi.models.V1PodStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @program: FlinkGateway
 * @description:
 * @author: yangliao
 * @create: 2021-07-09 10:42
 */
@Slf4j
@Service
public class K8sServiceImpl implements K8sService {

    @Resource
    private CoreV1Api api;

    @Override
    public List<ContainerGroup> getContainerGroup() {

        List<ContainerGroup> data = new ArrayList<>();

        try {
            V1PodList v1PodList = api.listNamespacedPod("flink", null, null, null, null, null, null, null, null, null, null);
            for (V1Pod item : v1PodList.getItems()) {
                ContainerGroup containerGroup = new ContainerGroup();
                V1ObjectMeta v1ObjectMeta = Objects.requireNonNull(item.getMetadata());
                containerGroup.setName(v1ObjectMeta.getName());

                Map<String, String> labels = v1ObjectMeta.getLabels();
                if (null != labels) {
                    containerGroup.setApp(labels.get("app"));
                    if (StringUtils.isBlank(labels.get("component"))) {
                        continue;
                    }
                    containerGroup.setComponent(labels.get("component"));
                }

                V1PodStatus status = item.getStatus();
                if (null != status) {
                    containerGroup.setHostIP(status.getHostIP());
                    containerGroup.setPhase(status.getPhase());

                    if (null != status.getContainerStatuses()) {
                        Integer restartCount = Objects.requireNonNull(status.getContainerStatuses()).get(0).getRestartCount();
                        containerGroup.setRestartCount(restartCount);
                    }
                }
                data.add(containerGroup);
            }
        } catch (Exception e) {
            log.error("", e);
        }

        return data;
    }

}
